package cfluo.study;

import java.util.ArrayList;

import org.drools.template.DataProviderCompiler;
import org.junit.Test;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.Message.Level;
import org.kie.api.builder.model.KieBaseModel;
import org.kie.api.builder.model.KieModuleModel;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;

import cfluo.study.fact.Message;
import cfluo.study.templates.MyDataProvider;

public class DroolsTest3 {
	/**
	 * 根据规则模板装载规则
	 */
	@Test
	public void DynamicRulesTest(){
		ArrayList<String[]> rows = new ArrayList<String[]>();  
        rows.add(new String[] { "1", "status == 0" });  
  
        MyDataProvider tdp = new MyDataProvider(rows);  
        DataProviderCompiler converter = new DataProviderCompiler();  
        String drl = converter.compile(tdp, "/rules/rule_template_1.drl");  
  
        System.out.println(drl);  
  
        KieServices kieServices = KieServices.Factory.get();  
//        KieResources resources = kieServices.getResources();  
        KieModuleModel kieModuleModel = kieServices.newKieModuleModel();//1  
  
        KieBaseModel baseModel = kieModuleModel.newKieBaseModel("FileSystemKBase").addPackage("rules");//2  
        baseModel.newKieSessionModel("FileSystemKSession");//3  
        KieFileSystem fileSystem = kieServices.newKieFileSystem();  
  
        String xml = kieModuleModel.toXML();  
        System.out.println(xml);//4  
        fileSystem.writeKModuleXML(xml);//5  
        fileSystem.write("src/main/resources/rules/rule1.drl", drl);  
        KieBuilder kb = kieServices.newKieBuilder(fileSystem);  
        kb.buildAll();//7  
        if (kb.getResults().hasMessages(Level.ERROR)) {  
            throw new RuntimeException("Build Errors:\n" + kb.getResults().toString());  
        }  
        KieContainer kContainer = kieServices.newKieContainer(kieServices.getRepository().getDefaultReleaseId());  
  
        KieSession kSession = kContainer.newKieSession("FileSystemKSession");  
  
        Message message = new Message();  
        message.setMsg("Hello World");  
        message.setStatus(Message.HELLO);  
  
        kSession.insert(message);  
        kSession.fireAllRules();  
        kSession.dispose();  
  
	}
}
